package com.easykoo.ioc.xml;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;

import com.easykoo.ioc.BeanDefinitionLoader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.io.SAXReader;

import com.easykoo.ioc.BeanFactory;
import com.easykoo.ioc.Exception.BeanWireException;
import com.easykoo.ioc.Exception.NoSuchBeanException;

public class XMLBeanDefinitionLoader implements BeanDefinitionLoader {
    private Log logger = LogFactory.getLog(this.getClass());
    private BeanFactory beanFactory;

    public XMLBeanDefinitionLoader(String filename) throws Exception {
        logger.debug("Start to load " + filename);
        SAXReader saxReader = new SAXReader();
        InputStream is = new FileInputStream(this.getClass().getClassLoader().getResource(filename).getPath());
        Document document = saxReader.read(is);

        Map<String, Object> beanMap = XMLParser.parse(document);
        logger.debug("Loaded " + filename);
        beanFactory = BeanFactory.getBeanFactory("xml");
        beanFactory.push(beanMap);
    }

    public Object getBean(String beanName) throws NoSuchBeanException,
            BeanWireException {
        return beanFactory.getBean(beanName);
    }

}
